# coding:utf-8
import pymongo

# 使用默认的host和port
db_client = pymongo.MongoClient()

# 自定义host和port参数
db_client = pymongo.MongoClient(host="localhost", port=27017)

# 使用标准的URI连接语法
db_client = pymongo.MongoClient('mongodb://localhost:27017/')

# 指定数据库
db = db_client['qidian']

db = db_client.qidian

# 指定集合 集合不存在会自动创建集合
db_collection = db['hot']

# 插入文档
nove1 = {'name': '太阳', 'author':'高楼', 'form':'连载', 'type':'玄幻'}
result = db_collection.insert_one(nove1)
print(result)
print(result.inserted_id)

nove21 = {'name': '月亮', 'author':'高山', 'form':'连载', 'type':'纪实'}
nove22 = {'name': '星星', 'author':'高原', 'form':'连载', 'type':'玄幻'}
result = db_collection.insert_many([nove21, nove22])
print(result)
print(result.inserted_ids)

# 查询文档
result = db_collection.find_one({'name': '月亮'})
print(result)

cursor = db_collection.find({})
cursor = db_collection.find({'type':'玄幻'})
print(cursor)
for one in cursor:
    print(one)

# 更新文档  $set 表示修改字段值  $unset 表示删除指定字段  $rename 表示重命名字段
filter = {'name': '帝国崛起'}
update = {'$set': {'type': '历史'}}
result = db_collection.update_one(filter, update)
print(result)
print(result.raw_result)
result = db_collection.update_many(filter, update)
print(result)
print(result.raw_result)

# 删除文档
result = db_collection.delete_one({'name': '星星'})
print(result)
print(result.raw_result)
result = db_collection.delete_many({'name': '星星'})
print(result)
print(result.raw_result)

# 关闭数据库
db_client.close()